package org.jackysoft.security.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.config.ResourceCache;
import org.jackysoft.entity.AcegiRole;
import org.jackysoft.entity.TreeNode;
import org.jackysoft.service.SecurityRoleService;
import org.jackysoft.service.TreeNodeService;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

@Component("resourceCache")
public class MySQLResourceCache  implements ResourceCache {
	
	private static final Log logger = LogFactory.getLog(MySQLResourceCache.class);
	private List<Resource> requestList = new ArrayList<Resource>();
	private List<String> unprotectedUrl = Lists.newArrayList();
	
	
	@PostConstruct
	public void init(){
		loadResource();
	}
	
	
	
	public void loadResource() {
		
		    logger.info("开始加载授权资源.....");
		
			requestList.clear();
		
			Collection<AcegiRole> sysroles =  acegiService.gets();
			
			for(AcegiRole role : sysroles){
				//加载公用的url
				for(String commonurl : unprotectedUrl){
					
					requestList.add(new Resource(commonurl.toLowerCase(), role.getName()));
				}
				
				//为每个role加载自己配置的url
				Collection<TreeNode> roleTrees = treeService.getsBySecurole(role);
				for(TreeNode tree : roleTrees){
					String uri = tree.getIdentifier().toLowerCase();
					requestList.add(new Resource(uri, role.getName()));
				}
			}
			
			 logger.info("授权资源加载完毕！");

	}

	public List<Resource> getRequestList() {
		return requestList;
	}

	public List<String> getUnprotectedUrl() {
		this.unprotectedUrl.clear();
		this.unprotectedUrl.add("/css/**");
		this.unprotectedUrl.add("/images/**");
		this.unprotectedUrl.add("/jsp/**");
		this.unprotectedUrl.add("/attachment/**");
		this.unprotectedUrl.add("/document/**");
		this.unprotectedUrl.add("/scripts/**");
	    return unprotectedUrl;
	}

	public void setUnprotectedUrl(List<String> unprotectedUrl) {
		this.unprotectedUrl = unprotectedUrl;
	}
	private TreeNodeService treeService;
	private SecurityRoleService acegiService;
	public TreeNodeService getTreeService() {
		return treeService;
	}

	@javax.annotation.Resource
	public void setTreeService(TreeNodeService treeService) {
		this.treeService = treeService;
	}

	public SecurityRoleService getAcegiService() {
		return acegiService;
	}

	@javax.annotation.Resource
	public void setAcegiService(SecurityRoleService acegiService) {
		this.acegiService = acegiService;
	}



	@Override
	public void reloadResource() {
		loadResource();		
	}

}
